import { base64_encode, base64_decode } from './base64.js';
import md5 from './md5.js'; 
var util = {};
import App from 'App'
var m = 'cyl_novel';
util.base64Encode = function (str) {
	return base64_encode(str)
}; 

util.base64Decode = function (str) {
	return base64_decode(str)
};
util.md5 = function (str) {
	return md5(str)
};
/**
	构造微擎地址, 
	@params action 微擎系统中的controller, action, do，格式为 'wxapp/home/navs'
	@params querystring 格式为 {参数名1 : 值1, 参数名2 : 值2}
*/
util.url =  function (action, querystring) {
	// #ifdef H5
	if(process.env.NODE_ENV === 'development'){
		var uniacid = 1;
		host = 'http://thecook.com.cn';
	}else{
		var host = location.origin
		var url = document.location.toString();
		var arrUrl = url.split("//");
		var start = arrUrl[1].indexOf("/");
		var relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符
		relUrl = relUrl.split("i=");
		relUrl = relUrl[1].split("&");
		var uniacid = relUrl[0];
	}
	var siteinfo = {
	  "uniacid": uniacid, 
	  "siteroot": host + "/app/index.php",
	};
	var url = siteinfo.siteroot + '?i=' + siteinfo.uniacid + '&c=entry&m=' + m +'&';
	if (action) {
		action = action.split('/');
		if (action[0]) {
			url += 'do=' + action[0] + '&';
		}				
	}
	// #endif
	// #ifndef H5
	
		// #ifdef APP-PLUS
		var siteinfo = {  
			"uniacid": "46",
			"acid": "46",
			"multiid": "0",
			"version": "1.0.0", 
			"siteroot": "https://sport.mtgjiaxiang.com/app/index.php",
		}
		var rom = 'phoneapp'; 
		// #endif  
		// #ifdef MP-WEIXIN
		var siteinfo = App.siteInfo;
		var rom = 'wxapp'; 
		// #endif
		if (action.indexOf('auth') != -1) {
			var url = siteinfo.siteroot + '?i=' + siteinfo.uniacid + '&t=' + siteinfo.multiid + '&v=' + siteinfo.version + '&from=' + rom +'&';
			if (action) {
				action = action.split('/');
				if (action[0]) {
					url += 'c=' + action[0] + '&';
				}
				if (action[1]) {
					url += 'a=' + action[1] + '&';
				}
				if (action[2]) {
					url += 'do=' + action[2] + '&';
				}
			}
		} else{
			var url = siteinfo.siteroot + '?i=' + siteinfo.uniacid + '&t=' + siteinfo.multiid + '&v=' + siteinfo.version + '&from=' + rom +'&c=entry&a=' + rom +'&m=' + m + '&';
			if (action) {
				action = action.split('/');
				if (action[0]) {
					url += 'do=' + action[0] + '&';
				}	
			}
		}
	// #endif	
	if (querystring && typeof querystring === 'object') {
		for (let param in querystring) {
            if (param && querystring.hasOwnProperty(param) && querystring[param]) {
				url += param + '=' + querystring[param] + '&';
			}
		}
	} 
	return url;
}

util.jssdk = function () {
	var wx = require('weixin-js-sdk');
	let url = location.href.split('#')[0]	
	util.get('jssdk',{'url':url})
	.then(res => {//data为一个数组，数组第一项为错误信息，第二项为返回数据
			wx.config({
				debug: false, // 开启调试模式,
				appId: res.appId, 
				timestamp: res.timestamp, 
				nonceStr: res.nonceStr, 
				signature: res.signature,
				jsApiList: [
					'checkJsApi',
					'onMenuShareTimeline',
					'onMenuShareAppMessage',
					'onMenuShareQQ',
					'onMenuShareWeibo',
					'hideMenuItems',
					'showMenuItems',
					'hideAllNonBaseMenuItem',
					'showAllNonBaseMenuItem',
					'translateVoice',
					'startRecord',
					'stopRecord',
					'onRecordEnd',
					'playVoice',
					'pauseVoice',
					'stopVoice',
					'uploadVoice',
					'downloadVoice',
					'chooseImage',
					'previewImage',
					'uploadImage',
					'downloadImage',
					'getNetworkType',
					'openLocation',
					'getLocation',
					'hideOptionMenu',
					'showOptionMenu',
					'closeWindow',
					'scanQRCode',
					'chooseWXPay',
					'openProductSpecificView',
					'addCard',
					'chooseCard',
					'openCard'	
				]
			});
	})
	return wx;
}
function getQuery(url) {
	var theRequest = [];
	if (url.indexOf("?") != -1) {
		var str = url.split('?')[1];
		var strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			if (strs[i].split("=")[0] && unescape(strs[i].split("=")[1])) {
				theRequest[i] = {
					'name': strs[i].split("=")[0],
					'value': unescape(strs[i].split("=")[1])
				}
			}
		}
	}
	return theRequest;
}
/*
* 获取链接某个参数
* url 链接地址
* name 参数名称
*/
function getUrlParam(url, name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象  
	var r = url.split('?')[1].match(reg);  //匹配目标参数  
	if (r != null) return unescape(r[2]); return null; //返回参数值  
}
/**
 * 获取签名 将链接地址的所有参数按字母排序后拼接加上token进行md5
 * url 链接地址
 * date 参数{参数名1 : 值1, 参数名2 : 值2} *
 * token 签名token 非必须
 */
function getSign(url, data, token) {
	var _ = require('./underscore.js');
	var md5 = require('./md5.js');
	var querystring = '';
	var sign = getUrlParam(url, 'sign');
	if (sign || (data && data.sign)) {
		return false;
	} else {
		if (url) {
			querystring = getQuery(url);
		}
		if (data) {
			var theRequest = [];
			for (let param in data) {
				if (param && data[param]) {
					theRequest = theRequest.concat({
						'name': param,
						'value': data[param]
					})
				}
			}
			querystring = querystring.concat(theRequest);
		}
		//排序
		querystring = _.sortBy(querystring, 'name');
		//去重
		querystring = _.uniq(querystring, true, 'name');
		var urlData = '';
		for (let i = 0; i < querystring.length; i++) {
			if (querystring[i] && querystring[i].name && querystring[i].value) {
				urlData += querystring[i].name + '=' + querystring[i].value;
				if (i < (querystring.length - 1)) {
					urlData += '&';
				}
			}
		}
		// #ifdef MP-WEIXIN
		token = token ? token : App.siteInfo.token;
		// #endif
		// #ifdef APP-PLUS
		token = 'cylddk';
		// #endif
		sign = md5(urlData + token);
		return sign;
	}
}
util.getSign = function (url, data, token) {
	return getSign(url, data, token);
};
/**
	二次封装微信wx.request函数、增加交互体全、配置缓存、以及配合微擎格式化返回数据

	@params option 弹出参数表，
	{
		url : 同微信, 
		data : 同微信,
		header : 同微信,
		method : 同微信,
		success : 同微信,
		fail : 同微信,
		complete : 同微信,

		cachetime : 缓存周期，在此周期内不重复请求http，默认不缓存
	}
*/
util.get = async function (url,option = {}){
	var url = util.url(url)
	return await new Promise((resolve, reject) => {  
			uni.request({  
					url: url,  
					data: option,  
					success: (res) => {  						
							resolve(res.data.data);  
					},  
					fail: (e) => {  
							reject(e);  
					}  
			})  
	})  
}
util.setting = async function (){
	var url = util.url('settings')
	return await new Promise((resolve, reject) => {  
			util.get('settings')
			.then(res => {			
				resolve(res); 
				return res
			})
	})	
}
util.request = function (option) {
	var _ = require('./underscore.js');
	var md5 = require('md5.js');
	var app = App;
	var option = option ? option : {};
	option.cachetime = option.cachetime ? option.cachetime : 0;
	option.showLoading = typeof option.showLoading != 'undefined' ? option.showLoading : true;
	var url = option.url;
	// #ifdef H5
	if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
		url = util.url(url);
	}	
	// #endif
	// #ifdef MP-WEIXIN || APP-PLUS	   
	var sessionid = uni.getStorageSync('userInfo').sessionid;
	if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
		url = util.url(url);
	}	
	var state = getUrlParam(url, 'state');
	if (!state && !(option.data && option.data.state) && sessionid) {
		url = url + '&state=we7sid-' + sessionid
	}	
	var sign = getSign(url, option.data);	
	if (sign) {
		url = url + "&sign=" + sign;
	}
	// #endif
	if (!url) {
		return false;
	}
	uni.showNavigationBarLoading();
	if (option.showLoading) {		
		util.showLoading();
	}
	if (option.cachetime) {
		var cachekey = md5(url);
		var cachedata = uni.getStorageSync(cachekey);
		var timestamp = Date.parse(new Date());		
		if (cachedata && cachedata.data) {
			if (cachedata.expire > timestamp) {
				if (option.complete && typeof option.complete == 'function') {
					option.complete(cachedata);
				}
				if (option.success && typeof option.success == 'function') {
					option.success(cachedata);
				}
				console.log('cache:' + url);
				uni.hideLoading();
				uni.hideNavigationBarLoading();
				return true;
			} else {
				uni.removeStorageSync(cachekey)
			}
		}
	}
	uni.request({
		'url': url,
		'data': option.data ? option.data : {},
		'header': option.header ? option.header : {},
		'method': option.method ? option.method : 'GET',
		'header': {
			'content-type': 'application/x-www-form-urlencoded'
		},
		'success': function (response) {			
			uni.hideNavigationBarLoading();
			uni.hideLoading();
			if (response.data.errno) {					
					if (response.data.errno == '41009') {
						uni.setStorageSync('userInfo', '');						
						// #ifdef MP-WEIXIN
						util.getUserInfo(function (res) {
							util.request(option)
						});
						// #endif						
						return;
					} else {
						if (option.fail && typeof option.fail == 'function') {
							option.fail(response);
						} else {
							if (response.data.message) {
								if (response.data.data != null && response.data.data.redirect) {
									var redirect = response.data.data.redirect;
								} else {
									var redirect = '';
								}
								util.message(response.data.message, redirect, 'error');
							}
						}
						return;
					}
        } else {
				if (option.success && typeof option.success == 'function') {
					option.success(response);
				}
				//写入缓存，减少HTTP请求，并且如果网络异常可以读取缓存数据
				if (option.cachetime) {
					var cachedata = { 'data': response.data, 'expire': timestamp + option.cachetime * 1000 };
					uni.setStorageSync(cachekey, cachedata);
				}
			}
		},
		'fail': function (response) {
			
			uni.hideNavigationBarLoading();
			uni.hideLoading();
			
			//如果请求失败，尝试从缓存中读取数据
			var md5 = require('md5.js');
			var cachekey = md5(url);
			var cachedata = uni.getStorageSync(cachekey);
			if (cachedata && cachedata.data) {
				if (option.success && typeof option.success == 'function') {
					option.success(cachedata);
				}
				console.log('failreadcache:' + url);
				return true;
			} else {
				if (option.fail && typeof option.fail == 'function') {
					option.fail(response);
				}
			}
		},
		'complete': function (response) {
			// uni.hideNavigationBarLoading();
			// uni.hideLoading();
			if (option.complete && typeof option.complete == 'function') {
				option.complete(response);
			}
		}
	});
}

util.appUserInfo = function (cb) {
	var login = function() {
		console.log('start login');
		var userInfo = {
			'sessionid': '',
			'wxInfo': '',
			'memberInfo': '',
		};
		uni.login({
			provider: 'weixin',
			success: function (res) {
				util.request({
					url: 'openid',
					data: { 
						openid1: res.authResult.openid ,
						unionid: res.authResult.unionid ,
						errMsg: res.authResult.errMsg ,
					},				
					showLoading:false,
					cachetime: 0,
					success: function (session) {							
						if (!session.data.errno) {
							userInfo.sessionid = session.data.data.sessionid
							uni.setStorageSync('userInfo', userInfo);
							uni.getUserInfo({
								provider: 'weixin',
								success: function (wxInfo) {									
									userInfo.wxInfo = wxInfo.userInfo
									uni.setStorageSync('userInfo', userInfo);									
									util.request({
										url: 'userinfo',
										data: {
											openId: res.authResult.openid,
											nickName: wxInfo.userInfo.nickName,
											gender: wxInfo.userInfo.gender,
											city: wxInfo.userInfo.city,
											province: wxInfo.userInfo.province,
											avatarUrl: wxInfo.userInfo.avatarUrl,
											unionid: res.authResult.unionid,  											
										},
										method: 'POST',
										header: {
											'content-type': 'application/x-www-form-urlencoded'
										}, 
										cachetime: 0,
										showLoading:false,
										success: function (res) {												
											if (!res.data.errno) {
												userInfo.memberInfo = res.data.data;
												uni.setStorageSync('userInfo', userInfo);
											}
											typeof cb == "function" && cb(userInfo);
										}
									});
								},
								fail: function () {
									typeof cb == "function" && cb(userInfo);
								},
								complete: function () {
								}
							})
						}
					}
				});
			}
		});
	};
	var app = uni.getStorageSync('userInfo');	
	login();	 
}

util.getWe7User = function (cb, code) {
  var userInfo = wx.getStorageSync('userInfo') || {};
  util.request({
    url: 'auth/session/openid',
    data: { code: code ? code : '' },
    cachetime: 0,
    showLoading: false,
    success: function (session) {
      if (!session.data.errno) {
        userInfo.sessionid = session.data.data.sessionid
        userInfo.memberInfo = session.data.data.userinfo
        wx.setStorageSync('userInfo', userInfo)
      }
      typeof cb == "function" && cb(userInfo);
    }
  });
}
util.upadteUser = function (wxInfo, cb) {
  var userInfo = uni.getStorageSync('userInfo');
  if (!wxInfo) {
    return typeof cb == "function" && cb(userInfo);;
  }
  userInfo.wxInfo = wxInfo.userInfo
  util.request({
    url: 'auth/session/userinfo',
    data: {
      signature: wxInfo.signature,
      rawData: wxInfo.rawData,
      iv: wxInfo.iv,
      encryptedData: wxInfo.encryptedData
    },
		showLoading: false,
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    cachetime: 0,
    success: function (res) {
      if (!res.data.errno) {
        userInfo.memberInfo = res.data.data;
        uni.setStorageSync('userInfo', userInfo);
      }
      typeof cb == "function" && cb(userInfo);
    }
  });
}
util.checkSession = function (option) {
  util.request({
    url: 'auth/session/check',
    method: 'POST',
    cachetime: 0,
    showLoading: false,
    success: function (res) {
      if (!res.data.errno) {
        typeof option.success == "function" && option.success();
      } else {
        typeof option.fail == "function" && option.fail();
      }
    },
    fail: function () {
      typeof option.fail == "function" && option.fail();
    }
  })
}
util.getUserInfo = function (cb, wxInfo) {
	var login = function() {
		console.log('start login');
		var userInfo = {
			'sessionid': '',
			'wxInfo': '',
			'memberInfo': '',
		};
		wx.login({
			success: function (res) {
				util.getWe7User(function(userInfo) {
					if (wxInfo) {
						util.upadteUser(wxInfo, function(userInfo) {
							typeof cb == "function" && cb(userInfo);
						})
					} else {
						if (wx.canIUse('getUserInfo')) {
							// 如果可用
							wx.getUserInfo({
								withCredentials: true,
								success: function(wxInfo){
									util.upadteUser(wxInfo, function(userInfo) {
										typeof cb == "function" && cb(userInfo);
									})
								},
								fail: function() {
									typeof cb == "function" && cb(userInfo);
								}
							})
						} else {
							typeof cb == "function" && cb(userInfo);
						}
					}
				}, res.code)
			},
			fail: function () {
				wx.showModal({
					title: '获取信息失败',
					content: '请允许授权以便为您提供给服务',
					success: function (res) {
						if (res.confirm) {
							util.getUserInfo();
						}
					}
				})
			}
		});
	};

	var userInfo = wx.getStorageSync('userInfo') || {};
	if (userInfo.sessionid) {
		util.checkSession({
			success: function(){
				if (wxInfo) {
					util.upadteUser(wxInfo, function(userInfo) {
						typeof cb == "function" && cb(userInfo);
					})
				} else {
					typeof cb == "function" && cb(userInfo);
				}
			},
			fail: function(){
				userInfo.sessionid = '';
				console.log('relogin');
				wx.removeStorageSync('userInfo');
				login();
			}
		})
	} else {
		//调用登录接口
		login();
	}
}
util.message = function(title, redirect, type) {
	if (!title) {
		return true;
	}
	if (typeof title == 'object') {
		redirect = title.redirect;
		type = title.type;
		title = title.title;
	}
	if (redirect) {
		var redirectType = redirect.substring(0, 9), url = '', redirectFunction = '';
		if (redirectType == 'navigate:') {
			redirectFunction = 'navigateTo';
			url = redirect.substring(9);
		} else if (redirectType == 'redirect:') {
			redirectFunction = 'redirectTo';
			url = redirect.substring(9);
		} else {
			url = redirect;
			redirectFunction = 'redirectTo';
		}
	}
	if (!type) {
		type = 'success';
	}

	if (type == 'success') {
		uni.showToast({
			title: title,
			icon: 'success',
			duration: 2000,
			mask : url ? true : false,
			complete : function() {
				if (url) {
					setTimeout(function(){
						wx[redirectFunction]({
							url: url,
						});
					}, 1800);
				}
				
			}
		});
	} else if (type == 'error') {
		uni.showModal({
			title: '系统信息',
			content : title,
			showCancel : false,
			complete : function() {
				if (url) {
					wx[redirectFunction]({
						url: url,
					});
				}
			}
		});
	}
}
//封装微信等待提示，防止ajax过多时，show多次
util.showLoading = function() {
	var isShowLoading = uni.getStorageSync('isShowLoading');
	if (isShowLoading) {
		uni.hideLoading();
		uni.setStorageSync('isShowLoading', false);
	}

	uni.showLoading({
		title : '加载中',
		complete : function() {
			uni.setStorageSync('isShowLoading', true);
		},
		fail : function() {
			uni.setStorageSync('isShowLoading', false);
		}
	});
}
util.navigateBack = function (obj) {
	let delta = obj.delta ? obj.delta : 1;
	if (obj.data) {
		let pages = getCurrentPages()
		let curPage = pages[pages.length - (delta + 1)];
		if (curPage.pageForResult) {
			curPage.pageForResult(obj.data);
		} else {
			curPage.setData(obj.data);
		}
	}
	uni.navigateBack({
		delta: delta, // 回退前 delta(默认为1) 页面
		success: function (res) {
			// success
			typeof obj.success == "function" && obj.success(res);
		},
		fail: function (err) {
			// fail
			typeof obj.fail == "function" && obj.fail(err);
		},
		complete: function () {
			// complete
			typeof obj.complete == "function" && obj.complete();
		}
	})
};
util.go = function (url,id) {
	if (id) {
		var url = '/pages/' + url + '?id=' + id
	}
	uni.navigateTo({
		url: url
	});
};
util.openURL = function (url) {
	// #ifdef APP-PLUS
	if(plus.runtime.isApplicationExist({pname:'com.pinduoduo.com',action:'pinduoduo://'})){  
		plus.runtime.openURL(url);
	}else{
		plus.runtime.openURL(url);
	}
	// #endif
};
util.isWeiXin=()=>{
  var ua = navigator.userAgent.toLowerCase();
  if (ua.indexOf('micromessenger') != -1) {
    return true;
  } else {
    return false;
  }
}
module.exports = util;